#!/usr/bin/env bash

# Exit on error
set -e

export ARCH=`uname -m`

if [ ! -d "$1" ] ; then
  echo "Error: Program folder $1 not found!"
  exit 1
fi

APPDIR=$1

wget -c -nv "https://github.com/AppImage/AppImageKit/releases/download/continuous/appimagetool-$ARCH.AppImage"
chmod a+x appimagetool-$ARCH.AppImage

cp AppRun.release $APPDIR/AppRun
cp metadata/org.freac.freac.desktop $APPDIR
cp $APPDIR/icons/freac.png $APPDIR/org.freac.freac.png

mkdir -p $APPDIR/usr/share/metainfo
cp metadata/org.freac.freac.appdata.xml $APPDIR/usr/share/metainfo

import_library () {
  libdirs=( /usr/local/lib/$ARCH-linux-gnu /usr/local/lib64 /usr/local/lib /usr/lib/$ARCH-linux-gnu /usr/lib64 /usr/lib )

  for libdir in ${libdirs[@]}; do
    if ls $libdir/$1* 1> /dev/null 2>&1; then
      cp $libdir/$1* $APPDIR
      return
    fi
  done

  echo "Error: Library $1 not found!"
  return 1
}

import_library libcurl.so
import_library libssh2.so
import_library libssl.so
import_library libcrypto.so

./appimagetool-$ARCH.AppImage $APPDIR $APPDIR.AppImage
